<template>
    <div class="page-container">
        <el-card class="box-card">
            <template #header>
                <div class="card-header">
                    <span class="title">出库管理</span>
                    <div class="header-actions">
                        <el-button type="primary" @click="handleAdd" class="add-button">
                            <el-icon><Plus /></el-icon>新增出库
                        </el-button>
                    </div>
                </div>
            </template>
            
            <!-- 搜索区域 -->
            <div class="search-area">
                <el-form :inline="true" :model="searchForm" class="demo-form-inline">
                    <el-form-item label="出库单号">
                        <el-input 
                            v-model="searchForm.orderId" 
                            placeholder="请输入出库单号" 
                            clearable 
                            prefix-icon="Search"
                            class="custom-input"
                        />
                    </el-form-item>
                    <el-form-item label="出库类型">
                        <el-select style="width: 240px" v-model="searchForm.orderType" placeholder="请选择出库类型" clearable>
                            <el-option 
                                v-for="item in orderTypes" 
                                :key="item.value" 
                                :label="item.label" 
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="出库时间">
                        <el-date-picker
                            v-model="searchForm.dateRange"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="YYYY-MM-DD"
                        />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleSearch" class="search-button">
                            <el-icon><Search /></el-icon>搜索
                        </el-button>
                        <el-button @click="resetForm" class="reset-button">
                            <el-icon><Refresh /></el-icon>重置
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>

            <!-- 表格区域 -->
            <el-table 
                :data="tableData" 
                style="width: 100%" 
                border 
                stripe
                @selection-change="handleSelectionChange"
                :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }"
                :row-style="{ height: '60px' }"
                :cell-style="{ padding: '8px 0' }"
                highlight-current-row
            >
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="序号" width="80" type="index" align="center" />
                <el-table-column prop="orderId" label="出库单号" min-width="150" align="center" show-overflow-tooltip />
                <el-table-column label="出库类型" width="120" align="center">
                    <template #default="{ row }">
                        <el-tag :type="row.orderType === 1 ? 'success' : 
                               row.orderType === 2 ? 'warning' : 'info'">
                            {{ row.typeName }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="customerName" label="客户名称" min-width="120" align="center" show-overflow-tooltip />
                <el-table-column prop="warehouseName" label="目标仓库" min-width="120" align="center" show-overflow-tooltip />
                <el-table-column prop="totalQuantity" label="总数量" width="100" align="center" />
                <el-table-column prop="operatorName" label="操作人" width="120" align="center" />
                <el-table-column label="状态" width="100" align="center">
                    <template #default="{ row }">
                        <el-tag :type="row.status === 0 ? 'warning' : 'success'">
                            {{ row.statusName }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" min-width="180" align="center" show-overflow-tooltip>
                    <template #default="{ row }">
                        {{ formatDate(row.createTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200" align="center" fixed="right">
                    <template #default="{ row }">
                        <div class="operation-buttons">
                            <el-tooltip content="查看" placement="top">
                                <el-button :icon="View" circle type="primary" @click="handleView(row)" size="small" />
                            </el-tooltip>
                            <el-tooltip content="审核" placement="top" v-if="row.status === 0">
                                <el-button :icon="Check" circle type="success" @click="handleApprove(row)" size="small" />
                            </el-tooltip>
                            <el-tooltip content="删除" placement="top" v-if="row.status === 0">
                                <el-button :icon="Delete" circle type="danger" @click="handleDelete(row)" size="small" />
                            </el-tooltip>
                        </div>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination
                    v-model:current-page="currentPage"
                    v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="total"
                    layout="total, sizes, prev, pager, next, jumper"
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>
        </el-card>

        <!-- 新增/查看对话框 -->
        <el-dialog 
            v-model="dialogVisible"
            :title="dialogType === 'view' ? '出库单详情' : '新增出库单'"
            width="60%"
            destroy-on-close
            class="custom-dialog"
            :show-close="false"
        >
            <template #header>
                <div class="dialog-header">
                    <div class="dialog-title">
                        <el-icon class="title-icon">
                            <component :is="dialogType === 'view' ? View : Plus" />
                        </el-icon>
                        <span>{{ dialogType === 'view' ? '出库单详情' : '新增出库单' }}</span>
                    </div>
                    <el-button class="close-button" @click="dialogVisible = false" circle>
                        <el-icon><Close /></el-icon>
                    </el-button>
                </div>
            </template>
            
            <div class="dialog-content">
                <el-form :model="form" label-width="100px" class="drawer-form">
                    <div class="form-section">
                        <h3>基本信息</h3>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="出库类型" required>
                                    <el-select 
                                        v-model="form.orderType" 
                                        placeholder="请选择出库类型"
                                        :disabled="dialogType === 'view'"
                                        @change="handleTypeChange"
                                        class="custom-input">
                                        <el-option 
                                            v-for="item in orderTypes" 
                                            :key="item.value" 
                                            :label="item.label" 
                                            :value="item.value"
                                        />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item 
                                    :label="form.orderType === 1 ? '客户' : '目标仓库'" 
                                    v-if="form.orderType === 1 || form.orderType === 2"
                                    required
                                >
                                    <el-select 
                                        v-model="targetId" 
                                        :placeholder="form.orderType === 1 ? '请选择客户' : '请选择目标仓库'"
                                        :disabled="dialogType === 'view'"
                                        class="custom-input">
                                        <el-option 
                                            v-for="item in form.orderType === 1 ? customers : warehouses" 
                                            :key="item.id" 
                                            :label="item.name" 
                                            :value="item.id"
                                        />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </div>

                    <el-divider />

                    <div class="form-section">
                        <div class="section-header">
                            <h3>商品明细</h3>
                            <el-button 
                                type="primary" 
                                @click="addRow" 
                                class="add-row-button"
                                v-if="dialogType !== 'view'"
                            >
                                <el-icon><Plus /></el-icon>添加商品
                            </el-button>
                        </div>
                        <el-table 
                            :data="form.details" 
                            style="width: 100%" 
                            border
                            :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }">
                            <el-table-column label="商品名称" min-width="200">
                                <template #default="scope">
                                    <el-select 
                                        v-model="scope.row.productId" 
                                        filterable 
                                        placeholder="请选择商品"
                                        :disabled="dialogType === 'view'"
                                        @change="(val) => handleProductChange(val, scope.$index)"
                                        class="custom-input">
                                        <el-option 
                                            v-for="item in products" 
                                            :key="item.id" 
                                            :label="item.name" 
                                            :value="item.id"
                                        />
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column label="数量" width="150">
                                <template #default="scope">
                                    <el-input-number 
                                        v-model="scope.row.quantity" 
                                        :min="1" 
                                        placeholder="请输入数量"
                                        :disabled="dialogType === 'view'"
                                        class="custom-input" 
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column label="批次号" min-width="150" prop="batchNo" align="center" />
                            <el-table-column label="操作" width="100" fixed="right" align="center" v-if="dialogType !== 'view'">
                                <template #default="scope">
                                    <el-button type="danger" @click="removeRow(scope.$index)" class="delete-button" link>
                                        删除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-form>
            </div>
            
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="handleSubmit" v-if="dialogType !== 'view'">
                        <el-icon><Check /></el-icon>确认
                    </el-button>
                    <el-button @click="dialogVisible = false">
                        <el-icon><Close /></el-icon>关闭
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import {
    Search,
    Refresh,
    Plus,
    View,
    Check,
    Close,
    Delete
} from '@element-plus/icons-vue'
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDate } from '@/utils/format.js'
import { 
    getOutboundListService,
    getOutboundDetailService,
    addOutboundService,
    approveOutboundService,
    deleteOutboundService
} from '@/api/inventory.js'

// 出库类型选项
const orderTypes = [
    { value: 1, label: '销售出库' },
    { value: 2, label: '调拨出库' },
    { value: 3, label: '报损出库' }
]

// 搜索表单
const searchForm = reactive({
    orderId: '',
    orderType: '',
    dateRange: []
})

// 表格数据
const tableData = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add') // add 或 view

// 表单数据
const form = reactive({
    orderType: '',
    customerId: '',
    toWarehouseId: '',
    details: []
})

// 模拟数据 - 实际项目中需要从后端获取
const customers = ref([
    { id: 1, name: '客户A' },
    { id: 2, name: '客户B' }
])
const warehouses = ref([
    { id: 1, name: '仓库A' },
    { id: 2, name: '仓库B' }
])

// 计算属性
const targetId = computed({
    get: () => form.orderType === 1 ? form.customerId : form.toWarehouseId,
    set: (val) => {
        if (form.orderType === 1) {
            form.customerId = val
        } else {
            form.toWarehouseId = val
        }
    }
})

// 获取出库单列表
const getOutboundList = async () => {
    try {
        const params = {
            pageNum: currentPage.value,
            pageSize: pageSize.value,
            orderId: searchForm.orderId,
            orderType: searchForm.orderType,
            startTime: searchForm.dateRange?.[0],
            endTime: searchForm.dateRange?.[1]
        }
        const res = await getOutboundListService(params)
        if (res.code === 0) {
            tableData.value = res.data.items
            total.value = res.data.total
        }
    } catch (error) {
        console.error('获取出库单列表失败:', error)
        ElMessage.error('获取出库单列表失败')
    }
}

// 搜索
const handleSearch = () => {
    currentPage.value = 1
    getOutboundList()
}

// 重置表单
const resetForm = () => {
    searchForm.orderId = ''
    searchForm.orderType = ''
    searchForm.dateRange = []
    handleSearch()
}

// 新增出库单
const handleAdd = () => {
    dialogType.value = 'add'
    dialogVisible.value = true
    form.orderType = ''
    form.customerId = ''
    form.toWarehouseId = ''
    form.details = [{
        productId: '',
        productName: '',
        quantity: 1
    }]
}

// 查看详情
const handleView = async (row) => {
    dialogType.value = 'view'
    dialogVisible.value = true
    try {
        const res = await getOutboundDetailService(row.orderId)
        if (res.code === 0) {
            Object.assign(form, res.data)
        }
    } catch (error) {
        console.error('获取出库单详情失败:', error)
        ElMessage.error('获取出库单详情失败')
    }
}

// 审核出库
const handleApprove = async (row) => {
    try {
        const result = await ElMessageBox.confirm(
            '确认要审核通过该出库单吗？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        
        if (result) {
            const res = await approveOutboundService({ orderId: row.orderId })
            if (res.code === 0) {
                ElMessage.success('审核成功')
                getOutboundList()
            }
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('审核出库单失败:', error)
            ElMessage.error('审核失败')
        }
    }
}

// 删除出库单
const handleDelete = async (row) => {
    try {
        const result = await ElMessageBox.confirm(
            '确认要删除该出库单吗？此操作不可恢复！',
            '警告',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        
        if (result) {
            const res = await deleteOutboundService(row.orderId)
            if (res.code === 0) {
                ElMessage.success('删除成功')
                getOutboundList()
            }
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除出库单失败:', error)
            ElMessage.error('删除失败')
        }
    }
}

// 出库类型变化
const handleTypeChange = () => {
    form.customerId = ''
    form.toWarehouseId = ''
}

// 商品列表响应式数据
const products = ref([])

import { getListService } from '@/api/goods'
// 获取商品列表方法
const fetchProducts = async () => {
  try {
    const response = await getListService()
    if (response?.code === 0 && Array.isArray(response.data)) {
      products.value = response.data.map(item => ({
        id: item.id,
        name: item.name
      }))
      console.log('商品列表获取成功，共获取', products.value.length, '条数据')
    } else {
      console.error('获取商品列表失败：', response?.message || '返回数据格式不正确')
      ElMessage.warning('商品列表获取失败，请刷新页面重试')
    }
  } catch (error) {
    console.error('获取商品列表异常：', error)
    ElMessage.error('获取商品列表出错，请稍后重试')
  }
}
// 在组件挂载时调用
onMounted(() => {
  fetchProducts()
})

// 商品选择变化
const handleProductChange = (value, index) => {
    const product = products.value.find(item => item.id === value)
    if (product) {
        form.details[index].productName = product.name
    }
}

// 添加商品行
const addRow = () => {
    form.details.push({
        productId: '',
        productName: '',
        quantity: 1
    })
}

// 删除商品行
const removeRow = (index) => {
    if (form.details.length > 1) {
        form.details.splice(index, 1)
    } else {
        ElMessage.warning('至少保留一行商品')
    }
}

// 提交表单
const handleSubmit = async () => {
    // 表单验证
    if (!form.orderType) {
        ElMessage.warning('请选择出库类型')
        return
    }
    if (form.orderType === 1 && !form.customerId) {
        ElMessage.warning('请选择客户')
        return
    }
    if (form.orderType === 2 && !form.toWarehouseId) {
        ElMessage.warning('请选择目标仓库')
        return
    }
    if (!form.details.length) {
        ElMessage.warning('请添加出库商品')
        return
    }
    for (const item of form.details) {
        if (!item.productId) {
            ElMessage.warning('请选择商品')
            return
        }
        if (!item.quantity) {
            ElMessage.warning('请输入商品数量')
            return
        }
    }

    try {
        const res = await addOutboundService(form)
        if (res.code === 0) {
            ElMessage.success('添加成功')
            dialogVisible.value = false
            getOutboundList()
        }
    } catch (error) {
        console.error('添加出库单失败:', error)
        ElMessage.error('添加失败')
    }
}

// 分页相关方法
const handleSizeChange = (val) => {
    pageSize.value = val
    getOutboundList()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    getOutboundList()
}

// 多选相关
const handleSelectionChange = (val) => {
    // 可以用于批量操作
    console.log('selected:', val)
}

// 页面加载时获取数据
onMounted(() => {
    getOutboundList()
})
</script>

<style lang="scss" scoped>
.page-container {
    padding: 20px;
    
    .box-card {
        margin-bottom: 20px;
    }
    
    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .title {
            font-size: 16px;
            font-weight: bold;
        }
        
        .header-actions {
            display: flex;
            gap: 10px;
        }
    }
    
    .search-area {
        margin-bottom: 20px;
    }
}

.operation-buttons {
    display: flex;
    gap: 8px;
    justify-content: center;
}

.dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #e4e7ed;
    
    .dialog-title {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 16px;
        font-weight: bold;
        
        .title-icon {
            font-size: 20px;
            color: var(--el-color-primary);
        }
    }
}

.dialog-content {
    padding: 20px;
    
    .form-section {
        margin-bottom: 30px;
        
        h3 {
            margin: 0 0 15px 0;
            font-size: 16px;
            color: #303133;
        }
    }
    
    .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
    }
}

:deep(.el-descriptions) {
    padding: 20px;
    background-color: #f5f7fa;
    border-radius: 4px;
}

:deep(.el-table) {
    margin-top: 10px;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.custom-input {
    width: 100%;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    padding: 20px;
    background-color: #fff;
    border-top: 1px solid #e4e7ed;
}

.add-row-button {
    padding: 8px 16px;
    font-size: 14px;
    border-radius: 4px;
    display: inline-flex !important;
    align-items: center;
    gap: 5px;
    background-color: var(--el-color-primary) !important;
    border-color: var(--el-color-primary) !important;
    color: white !important;
    cursor: pointer;
    
    &:hover {
        background-color: var(--el-color-primary-light-3) !important;
        border-color: var(--el-color-primary-light-3) !important;
    }
    
    .el-icon {
        margin-right: 4px;
        font-size: 16px;
    }
}
</style> 